<template>
    <!-- 小额免密功能设置 -->
    <div
        class="smallAmtFreePwdSetting"
        v-loading="pageLoading"
        element-loading-background="rgba(255, 255, 255, 0.7)"
    >
        <cardComponent pageTitle="小额免密功能设置">
            <template slot="cardBody">
                <el-form v-model="searchFormOne" label-width="180px" size="small">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="账户类别:" class="text_fl">
                                <el-select
                                    v-model="searchForm.accttype"
                                    placeholder="请选择账户类别"
                                    clearable
                                    @change="changeCardList"
                                >
                                    <el-option
                                        v-for="item in AccountionTYPE_INFO"
                                        :label="item.label"
                                        :value="item.code"
                                        :key="item.label"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <!-- 卡列表 -->
                <div align="center">
                    <el-table
                        :data="cardList"
                        style="width: 95%"
                        border
                        stripe
                        class="table_head heard-bg setbottomborder"
                    >
                        <el-table-column label="卡号" min-width="80">
                            <template slot-scope="scope">{{ scope.row.CARDNBR }}</template>
                        </el-table-column>
                        <el-table-column label="卡片状态" min-width="80">
                            <template
                                slot-scope="scope"
                            >{{ scope.row.CARDSTAT|formcardsts(cardstsList) }}</template>
                        </el-table-column>
                        <el-table-column label="小额免密设置状态" min-width="80">
                            <template slot-scope="scope">{{ scope.row.UNQPASS?'开通':'关闭' }}</template>
                        </el-table-column>
                        <el-table-column label="操作" min-width="80">
                            <template slot-scope="scope">
                                <el-switch
                                    v-model="scope.row.UNQPASS"
                                    active-text="开通"
                                    inactive-text="关闭"
                                    @change="changeSetting(scope.row.CARDNBR,scope.row.UNQPASS)"
                                ></el-switch>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 话术 -->
                    <div div class="hstable_wrap" v-if="speechList.length!=0">
                        <el-table
                            :data="speechList"
                            border
                            stripe
                            header-row-class-name="headerRow"
                            ref="showListTable"
                            class="heard-bg business_table hstable"
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" label=" " min-width="55"></el-table-column>
                            <el-table-column label="业务话术">
                                <template slot-scope="scope">{{scope.row.content}}</template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div v-show="successFlag" align="center" style="margin-top:10px;">
                        <el-table
                            :data="tryData"
                            border
                            stripe
                            class="heard-bg business_table"
                            style="width: 100%;"
                            size="small"
                        >
                            <el-table-column label="操作结果">
                                <el-table-column prop="CARDNO" label="信用卡号"></el-table-column>

                                <el-table-column prop="PREVAL" label="交易结果"></el-table-column>

                                <el-table-column prop="AFTVAL" label="结果描述"></el-table-column>
                            </el-table-column>
                        </el-table>
                        <div align="center" style="margin-top:10px;">
                            <el-col :span="24">
                                <el-button
                                    plain
                                    type="primary"
                                    icon="el-icon-search"
                                    @click="updatehistory"
                                >修改记录查询</el-button>
                            </el-col>
                        </div>
                    </div>
                </div>
            </template>
        </cardComponent>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import { getAccountTypeName, getDictSelectList, getBusinessMenuId } from '@/utils/Common';
import { RegConfig } from '@/utils/RegConfig';
import cardComponent from '@/components/cardComponent/cardComponent.vue';

export default {
    name: 'smallAmtFreePwdSetting',
    components: {
        cardComponent,
    },
    data() {
        const validatorPass = (rule, value, callback) => {
            if (value > this.amount) {
                callback(new Error('高于账户额度，无法调整'));
            } else {
                callback();
            }
        };
        return {
            searchFormOne: {
                CARDNO: '',
                // 银联境内小额支付是否允许
            },
            searchForm: { // 搜索表单字段
                CARDNO: '',
                optionsLable: '44',
                // 状态
                UNQPASS: '',
                // 单笔支付
                QPASSAMT: '',
                // 每日支付
                QPASSAMTD: '',
                // 服务类型
                SERTYPE: '',
                // 修改内容
                CHGPARAM: '',
                allowOrNot: '',
                accttype: '',
                cardno: '',

            },
            // 判断是查询还是修改
            searchOrUpdate: '0',
            amount: Number,
            pageLoading: true,
            setcard4058: '',
            // 表单下拉
            formSelect: [
                {
                    label: '银联境内闪付小额免密',
                    value: 44,
                },
                {
                    label: '单笔银联境内闪付小额免密限额',
                    value: 45,
                },
                {
                    label: '每日银联境内闪付小额免密限额',
                    value: 46,
                },

            ],
            dialogVisible: false,
            rules: {
                CHGPARAM: [
                    { required: true, message: '请输入新内容', trigger: 'blur' },
                    { pattern: RegConfig.integerAmount, message: '请输入整数，首位不可为0', trigger: 'blur' },
                    { validator: validatorPass, trigger: 'blur' },
                ],
                optionsLable: [
                    { required: true, message: '请选择所需参数', trigger: 'blur' },
                ],
                allowOrNot: [
                    { required: true, message: '请选择小额免密状态', trigger: 'blur' },
                ],
            },
            accountType: '',
            cardList: [],
            cardFreePwdStatusTemp: '', //卡免密状态临时变量 0-默认、1-禁止、2-允许；0,1关闭、2开通
            cardstsList: [],
            successFlag: false,
            tryData: [
                {
                    CARDNO: '',
                    PREVAL: '',
                    AFTVAL: ''
                },
            ],
            speechList: [],//话术列表
            selectedList: [],
            MenuId: '',
        };
    },
    async mounted() {
        this.MenuId = this.$route.params.id || '';
        this.amount = this.cardInfo_3004.AVLIMT;
        this.cardstsList = await getDictSelectList('CLOCD', this);
        this.searchFormOne.CARDNO = this.cardInfo_3004.CARDNO;
        this.accountType = await getAccountTypeName(this.cardList_3601, this.cardInfo_3004, this);
        // 账户类型初始化
        this.searchForm.accttype = this.cardInfo_3004.CATEGORY + '';
        // 卡片列表初始化
        this.changeCardList(this.searchForm.accttype);
        await this.getspeechList();
    },
    filters: {
        // formcardsts(val, cardstsList) {
        //     if (val === '') {
        //         return '正常';
        //     }
        //     for (let index = 0; index < cardstsList.length; index++) {
        //         const element = cardstsList[index];
        //         if (element.code === val) {
        //             return element.label;
        //         }
        //     }

        // },
        formcardsts: (value, cardstsList) => {
            value = (`${value}`).trim();
            if (value === '') {
                return '正常';
            }
            for (let index = 0; index < cardstsList.length; index++) {
                const element = cardstsList[index];
                if (element.code === value) {
                    return element.label;
                }
            }
        },
    },
    computed: mapState({
        cardInfo_3004: state => state.common.cardInfo_3004,
        cardList_3601: state => state.common.cardList_3601,
        defaultParams: state => state.common.defaultParams,
        defaultpinFlag: state => state.common.pinFlag,
        AccountionTYPE_INFO: state => state.common.AccountionTYPE_INFO, //账户类别列表
        isCurrentMenuInfo: state => state.menu.isCurrentMenuInfo,
        businessMenu: state => state.menu.businessMenu,
    }),
    methods: {
        async changeCardList(val) {
            console.log("当前账户类型：" + val);
            let hasDefault = false; //是否包含默认卡
            this.cardList = [];
            let datalist = [];

            for (let index = 0; index < this.cardList_3601.length; index++) {
                const item = this.cardList_3601[index];
                if (item.CATEGORY + '' === val) {
                    await this.hanleSure(item.CARDNBR); //查询小额免密状态
                    item.UNQPASS = this.cardFreePwdStatusTemp; //将小额免密状态更新到卡列表
                    if (this.cardFreePwdStatusTemp == 2) {
                        item.UNQPASS = true;
                    } else {
                        item.UNQPASS = false;
                    }
                    // console.log("=========查询增加卡片小额免密状态，cardNo：%s，unqpass：%s", item.CARDNBR, item.UNQPASS);
                    datalist.push(item);
                    // console.log('=========after push datalist-', datalist);
                    if (item.CARDNBR === this.cardInfo_3004.CARDNO) {
                        hasDefault = true;
                    }
                }

            }
            this.cardList = JSON.parse(JSON.stringify(datalist));
            console.info("当前账户卡列表cardList：", this.cardList);

            //包含默认卡，卡号显示默认卡，不包含，显示cardList里第一张卡号
            if (hasDefault) {
                this.searchForm.cardno = this.cardInfo_3004.CARDNO;
            } else {
                this.searchForm.cardno = this.cardList[0].CARDNBR;
            }


        },
        //根据菜单id查询话术列表
        async getspeechList() {
            console.log("this.isCurrentMenuInfo.id", this.isCurrentMenuInfo.id);
            console.log("this.MenuId", this.MenuId);
            var checkParam = {
                'id': this.MenuId || this.isCurrentMenuInfo.id,
            };
            this.$post.busiMenu.getlistByMenuId(checkParam).then((res) => {
                console.log("话术查询结果：", res);
                if (res.status === 200) { // http通讯成功
                    if (res.data.status == 0) { // 业务请求成功
                        this.speechList = res.data.content;
                    }
                }
            });
        },
        handleSelectionChange(val) {
            this.selectedList = val;
        },
        // 点击确定按钮进行查询
        async hanleSure(cardNo) {
            this.searchOrUpdate = '0';
            this.dialogVisible = true;
            await this.hanleTableData(cardNo);
        },
        // 点击修改按钮
        async hanleUpdate(cardNo, unqpass) {
            this.searchOrUpdate = '1';
            await this.$confirm('确认修改？', '提示', { customClass: 'warning', type: 'warning' }).then(async () => {
                await this.hanleTableData(cardNo);

            }).catch(() => {
                console.log("quxiao");

                for (let index = 0; index < this.cardList.length; index++) {
                    const item = this.cardList[index];
                    if (item.CARDNBR + '' === cardNo) {
                        if (unqpass) {
                            item.UNQPASS = false;
                        } else {
                            item.UNQPASS = true;
                        }
                    }
                }
            });
        },
        // 走4058交易
        async hanleTableData(cardNo) {
            console.info('============4058-操作类型：' + this.searchOrUpdate + '卡号：' + cardNo);
            let CHGPARAM = '';
            // if (this.searchForm.optionsLable === 44) {
            //     CHGPARAM = `${this.searchForm.allowOrNot}`;
            // } else {
            //     CHGPARAM = this.searchForm.CHGPARAM;
            // }
            this.searchForm.optionsLable = 44; //服务类型   44-禁止境内闪付小额免密
            CHGPARAM = this.cardFreePwdStatusTemp;
            console.info('============4058-参数CHGPARAM：' + CHGPARAM);

            const appBody = {
                CARDNO: cardNo, // 卡号
                PINFLAG: this.defaultpinFlag, // 是否检查密码标志
                OPTION: this.searchOrUpdate, // 修改选项   0为查询  1为修改
                SERTYPE: this.searchForm.optionsLable, // 服务类型  查询时无作用
                CHGPARAM, // 修改内容，查询时无作用
            };
            const defaultParams = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParams.body.appHead.tranCode = '4058';
            defaultParams.body.appBody = appBody;
            console.info('============4058-参数defaultParams：', defaultParams);
            // 4058交易
            await this.$post.common.transPort(defaultParams).then((res) => {
                this.pageLoading = false;
                if (res.status === 200) {
                    const result = JSON.parse(res.data.jsonRes);
                    // console.log(result, 111111)
                    if (result.sysHead.rspCd === '000000') {
                        this.setcard4058 = result.body.appBody || [];
                        if (this.searchOrUpdate === '1') { //修改
                            // this.$alert('修改成功', '提示', {
                            //     customClass: 'success', type: 'success',
                            // });
                            this.successFlag = true;

                            this.tryData = [{
                                CARDNO: cardNo,
                                PREVAL: '交易成功',
                                AFTVAL: '',

                            }];
                            this.changeCardList(this.searchForm.accttype + ''); //重新加载卡列表信息
                        } else { //查询
                            this.cardFreePwdStatusTemp = result.body.appBody.UNQPASS || '';
                            console.info('============4058-查询结果UNQPASS：' + this.cardFreePwdStatusTemp);
                        }
                    } else {
                        if (this.searchOrUpdate === '1') { //修改
                            // this.$alert('修改成功', '提示', {
                            //     customClass: 'success', type: 'success',
                            // });
                            this.successFlag = true;

                            this.tryData = [{
                                CARDNO: cardNo,
                                PREVAL: '交易失败',
                                AFTVAL: result.sysHead.rspMsg,

                            }];
                        } else {
                            const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspMsg}`;
                            this.$alert(errorMsg, '提示', {
                                customClass: 'error', type: 'error',
                            });
                        }

                    }
                } else {
                    this.$alert('请求失败！', '提示', {
                        customClass: 'error', type: 'error',
                    });
                }
            });
        },

        async changeSetting(cardNo, unqpass) {

            console.log("this.selectedList.length", this.selectedList.length);
            if (this.selectedList.length != this.speechList.length) {
                this.$alert('话术尚未全部勾选！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                for (let index = 0; index < this.cardList.length; index++) {
                    const item = this.cardList[index];
                    if (item.CARDNBR + '' === cardNo) {
                        if (unqpass) {
                            item.UNQPASS = false;
                        } else {
                            item.UNQPASS = true;
                        }
                    }
                }
                return;
            }
            //操作状态
            // console.log("unqpass:", unqpass);
            if (unqpass == true) {
                this.cardFreePwdStatusTemp = 2;
            } else {
                this.cardFreePwdStatusTemp = 1;
            }
            await this.hanleUpdate(cardNo, unqpass); //修改

        },
        //修改记录查询
        updatehistory() {
            this.MenuId = getBusinessMenuId('/businessSystem/accountCardDetaileQuery', this.businessMenu);
            console.log('this.MenuId____', this.MenuId);
            this.$router.push({ name: 'accountCardDetaileQuery', path: '/businessSystem/accountCardDetaileQuery', params: { id: this.MenuId } });
        },
    },
};
</script>

<style lang='scss'>
.smallAmtFreePwdSetting {
    width: 98%;
    background: #fff;
    // padding:10px;
    box-sizing: border-box;
    border-radius: 5px;

    .bot {
        padding-left: 20px;
    }
    .setbottomborder .el-table__body-wrapper {
        max-height: 280px;
        overflow: hidden;
        overflow-y: auto;
    }
    /* //头部内容 */
    .tab-header {
        width: 100%;
        text-align: left;
        span {
            font-size: 14px;
        }
        .headerTitle {
            font-size: 16px;
            margin: 10px 0px;
            color: skyblue;
        }
    }
    .btnBox {
        text-align: center;
    }
    .dialogVisible {
        margin: 30px auto 0;
        .el-form-item__content {
            text-align: center;
        }
    }
}
</style>
